<template>
  <q-dialog
    v-model="webStore.loginDig"
    @hide="
      () => {
        loginTab = 'codeLogin'
        fromTab = 'login'
      }
    "
  >
    <q-card class="min-w-md">
      <div class="text-center q-pt-md">
        <q-img src="/images/yuanlogo3x.png" width="150px" />
      </div>
      <div class="flex flex-col items-center">
        <q-tab-panels v-model="fromTab" animated class="w-full">
          <q-tab-panel name="login">
            <q-tabs v-model="loginTab" class="text-primary">
              <q-tab name="codeLogin" label="验证码登录" />
              <q-tab name="passwdLogin" label="密码登录" />
            </q-tabs>
            <q-tab-panels v-model="loginTab" animated class="w-full">
              <q-tab-panel name="codeLogin">
                <form @submit.prevent="codeLoginFun">
                  <q-input v-model="codeLoginParm.loginName" type="email" label="邮箱" outlined />
                  <q-input
                    v-model="codeLoginParm.code"
                    type="text"
                    label="验证码"
                    outlined
                    class="mt-5"
                  >
                    <template v-slot:after>
                      <q-btn
                        :disable="loading"
                        :loading="loading"
                        @click="
                          () => {
                            checkCodeLogin()
                          }
                        "
                        color="blue-8"
                        label="发送验证码"
                      >
                        <template v-slot:loading>
                          {{ loadingText }}
                        </template>
                      </q-btn>
                    </template>
                  </q-input>
                  <div class="q-my-sm">
                    <span class="text-gray-4"> 登录成功后，未注册的邮箱会直接注册 </span>
                  </div>

                  <q-btn
                    type="submit"
                    :loading="loginBtnLoad"
                    class="w-full h-12"
                    color="blue-8"
                    label="登录"
                  />
                </form>
              </q-tab-panel>
              <q-tab-panel name="passwdLogin">
                <form @submit.prevent="passwdLogin">
                  <q-input v-model="passwdLoginParm.loginName" type="email" label="邮箱" outlined />
                  <q-input
                    v-model="passwdLoginParm.passwd"
                    type="password"
                    label="密码"
                    outlined
                    class="mt-5"
                  >
                  </q-input>
                  <div class="q-my-sm">
                    <span
                      @click="
                        () => {
                          fromTab = 'changePd'
                        }
                      "
                      class="text-blue-8 cursor-pointer"
                    >
                      忘记密码?
                    </span>
                  </div>

                  <q-btn
                    type="submit"
                    :loading="loginBtnLoad"
                    class="w-full h-12"
                    color="blue-8"
                    label="登录"
                  />
                </form>
              </q-tab-panel>
            </q-tab-panels>
          </q-tab-panel>
          <q-tab-panel name="changePd">
            <form @submit.prevent="changePdFun">
              <q-input v-model="changePdParam.loginName" type="email" label="邮箱" outlined />
              <q-input
                v-model="changePdParam.code"
                type="text"
                label="验证码"
                outlined
                class="mt-5"
              >
                <template v-slot:after>
                  <q-btn
                    :disable="loading"
                    :loading="loading"
                    @click="
                      () => {
                        checkCodeChangePd()
                      }
                    "
                    color="blue-8"
                    label="发送验证码"
                  >
                    <template v-slot:loading>
                      {{ loadingText }}
                    </template>
                  </q-btn>
                </template>
              </q-input>

              <q-input
                v-model="changePdParam.passwd"
                :type="passShow[0] ? 'password' : 'text'"
                label="输入密码"
                outlined
                class="mt-5"
                :rules="[(val) => checkPd(val) || '密码必须包含字母和数字，至少8位']"
              >
                <template v-slot:append>
                  <q-icon
                    :name="passShow[0] ? 'visibility_off' : 'visibility'"
                    class="cursor-pointer"
                    @click="passShow[0] = !passShow[0]"
                  />
                </template>
              </q-input>

              <q-input
                v-model="changePdParam.passwd2"
                :type="passShow[1] ? 'password' : 'text'"
                label="再输一次密码"
                outlined
                class="mt-5"
                :rules="[(val) => val == changePdParam.passwd || '两次输入密码不一致']"
              >
                <template v-slot:append>
                  <q-icon
                    :name="passShow[1] ? 'visibility_off' : 'visibility'"
                    class="cursor-pointer"
                    @click="passShow[1] = !passShow[1]"
                  />
                </template>
              </q-input>
              <div class="q-my-sm">
                <span class="text-gray-4"> 修改成功会自动登录 </span>
              </div>
              <q-btn
                type="submit"
                :loading="loginBtnLoad"
                class="w-full h-12"
                color="blue-8"
                label="修改密码"
              />
            </form>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </q-card>
  </q-dialog>

  <q-dialog
    @show="
      () => {
        openCaptcha()
      }
    "
    v-model="sendCodeDig"
  >
    <div id="captcha-box"></div>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useWebStore } from 'src/stores/webStore'
import {
  authCodeLogin,
  authPasswdLogin,
  authSendCode,
  authSetPasswdLogin,
  globalCaptcha,
  globalCaptchaCheck,
} from 'src/service/api'
import { patterns } from 'quasar'
import { checkPd, useYuan } from 'src/use'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare let initTAC: any

const { testPattern } = patterns
const { Info, Ok, Fail } = useYuan()

const webStore = useWebStore()

const loading = ref(false)

const loadingTime = ref(60)

const loadingText = ref('发送邮件中...')

const loginBtnLoad = ref(false)

const passShow = ref([true, true])

/* 密码登录参数 */
const passwdLoginParm = ref({
  loginName: '001@1.com',
  passwd: '000000',
})
/* 验证码登录参数 */
const codeLoginParm = ref({
  loginName: '',
  code: '',
})

/* 忘记密码修改密码参数 */
const changePdParam = ref({
  loginName: '',
  code: '',
  passwd: '',
  passwd2: '',
})
// 验证码弹窗
const sendCodeDig = ref(false)

// 登录Tab，验证码登录/密码登录
const loginTab = ref<'codeLogin' | 'passwdLogin'>('codeLogin')

// 登录修改页面
const fromTab = ref<'login' | 'changePd'>('login')

/* 打开验证码之前 */
const beferOpenCaptcha = (loginName: string) => {
  const checkRes = checkLoginName(loginName)
  if (checkRes != 'succ') {
    return Fail(checkRes)
  }
  sendCodeDig.value = true
}

/* 校验验证码登录 */
const checkCodeLogin = () => {
  beferOpenCaptcha(codeLoginParm.value.loginName)
}

/* 校验修改密码 */
const checkCodeChangePd = () => {
  beferOpenCaptcha(changePdParam.value.loginName)
}

/* 校验邮箱 */
const checkLoginName = (loginName: string) => {
  if (!loginName) return '邮箱不可为空'
  if (!testPattern.email(loginName)) {
    return '请输入正确的邮箱'
  }
  return 'succ'
}

/* 密码登录 */
const passwdLogin = async () => {
  const checkRes = checkLoginName(passwdLoginParm.value.loginName)
  if (checkRes != 'succ') {
    return Fail(checkRes)
  }

  if (!passwdLoginParm.value.passwd) return Fail('密码不可为空')

  loginBtnLoad.value = true
  const { data, error } = await authPasswdLogin(passwdLoginParm.value)
  loginBtnLoad.value = false
  if (!error) {
    loginSuccess(data)
  }
}

/* 登录成功 */
const loginSuccess = async (data: Api.TokenInfoVO) => {
  await webStore.loginSucc(data)
  Info('登录成功, 欢迎回来~~')
  // 刷新页面
  location.reload()
}

/* 验证码登录 */
const codeLoginFun = async () => {
  const checkRes = checkLoginName(codeLoginParm.value.loginName)
  if (checkRes != 'succ') {
    return Fail(checkRes)
  }
  if (!codeLoginParm.value.code) return Fail('验证码不可为空')
  loginBtnLoad.value = true
  const { data, error } = await authCodeLogin(codeLoginParm.value)
  loginBtnLoad.value = false
  if (!error) {
    loginSuccess(data)
  }
}

/* 修改密码 */
const changePdFun = async () => {
  const checkRes = checkLoginName(changePdParam.value.loginName)
  if (checkRes != 'succ') {
    return Fail(checkRes)
  }
  if (!changePdParam.value.code) return Fail('验证码不可为空')
  loginBtnLoad.value = true
  const { data, error } = await authSetPasswdLogin(changePdParam.value)
  loginBtnLoad.value = false
  if (!error) {
    loginSuccess(data)
  }
}

/* 验证码相关 */
const openCaptcha = () => {
  const config = {
    // 生成接口
    requestCaptchaDataUrl: globalCaptcha,
    // 验证接口
    validCaptchaUrl: globalCaptchaCheck,
    // 验证码绑定的div块
    bindEl: '#captcha-box',
    // 验证成功回调函数
    validSuccess: (
      res: {
        code: number
        msg: string
        data: { id: string }
        success: boolean
      },
      _c: never,
      tac: { destroyWindow: () => void },
    ) => {
      loading.value = true
      sendCodeDig.value = false
      // 销毁验证码服务
      tac.destroyWindow()
      authSendCode({
        id: res.data.id,
        loginName:
          fromTab.value == 'changePd'
            ? changePdParam.value.loginName
            : codeLoginParm.value.loginName,
        mark: fromTab.value,
      }).then(({ error }) => {
        if (!error) {
          Ok('验证码发送成功')
          const interval = setInterval(() => {
            loadingTime.value--
            loadingText.value = loadingTime.value + '秒后重发'
            if (loadingTime.value == 0) {
              clearInterval(interval)
              loadingTime.value = 60
              loadingText.value = '发送邮件中...'
              loading.value = false
            }
          }, 1000)
        } else {
          loading.value = false
        }
      })
    },
    validFail: (
      _res: { code: number; msg: string; success: boolean },
      _c: never,
      tac: { reloadCaptcha: () => void },
    ) => {
      tac.reloadCaptcha()
    },
    btnRefreshFun: (_c: never, tac: { reloadCaptcha: () => void }) => {
      tac.reloadCaptcha()
    },
    btnCloseFun: (_c: never, tac: { destroyWindow: () => void }) => {
      sendCodeDig.value = false
      tac.destroyWindow()
    },
  }
  const style = {
    // 配置样式， logoURL地址
    logoUrl: '/images/yuanlogo.png',
  }

  initTAC('./tac', config, style)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    .then((tac: any) => {
      tac.init() // 调用init则显示验证码
    })
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    .catch((e: any) => {
      console.log('初始化tac失败', e)
    })
}
</script>

<style scoped></style>
